package web.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import web.entity.LoginUser;
import web.entity.User;
import web.service.LoginService;
import web.utils.JwtUtil;
import web.utils.RedisCache;
import web.utils.ResponseResult;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;

    @Value("${redis_conf.login-prefix}")
    String redisPrefix;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("xxxxx");
        }

        //如果账号密码比对成功,则authenticate不为空
        //authenticate-->id--->token
        LoginUser ss = (LoginUser) authenticate.getPrincipal();
        String id = ss.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(id);
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("token", jwt);

        try {
            redisCache.setTTL(redisPrefix + id, ss);
        } catch (Exception e) {
            e.printStackTrace();
//            redis插入值失败: ①redis服务未启用
            return new ResponseResult(500, "cach error");
        }

        return new ResponseResult(200, "登录成功", objectObjectHashMap);

    }

    @Override
    public ResponseResult logout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        Long id = user.getUser().getId();
        redisCache.deleteObject(redisPrefix + id);
        return new ResponseResult(200, "注销成功");
    }
}
